import React, { useEffect, useState } from 'react';
import { PageContainer } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import { Button, Modal, Form, Input, InputNumber, Select, message, Space, Popconfirm } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import { getProductTagList, createProductTag, updateProductTag, deleteProductTag } from '@/services/ant-design-pro/product';

interface TagItem {
    id: string;
    name: string;
    status: number;
    sort: number;
    createdAt?: string;
    updatedAt?: string;
}

const ProductTagPage: React.FC = () => {
    const [modalVisible, setModalVisible] = useState(false);
    const [editingTag, setEditingTag] = useState<TagItem | null>(null);
    const [form] = Form.useForm();
    const actionRef = React.useRef<any>();

    // 创建或更新标签
    const handleSubmit = async (values: any) => {
        try {
            if (editingTag) {
                // 更新标签
                const response = await updateProductTag({
                    id: editingTag.id,
                    ...values
                });
                if (response?.code === 1) {
                    message.error('更新标签失败');
                    return;
                }
                message.success('更新标签成功');
            } else {
                // 创建标签
                const response = await createProductTag(values);
                if (response?.code === 1) {
                    message.error('创建标签失败');
                    return;
                }
                message.success('创建标签成功');
            }
            
            setModalVisible(false);
            setEditingTag(null);
            form.resetFields();
            actionRef.current?.reload();
        } catch (error) {
            message.error('操作失败');
        }
    };

    // 删除标签
    const handleDelete = async (id: string) => {
        try {
            const response = await deleteProductTag(id);
            if (response?.code === 1) {
                message.error('删除标签失败');
                return;
            }
            message.success('删除标签成功');
            actionRef.current?.reload();
        } catch (error) {
            message.error('删除标签失败');
        }
    };

    // 打开编辑模态框
    const handleEdit = (record: TagItem) => {
        setEditingTag(record);
        form.setFieldsValue(record);
        setModalVisible(true);
    };

    // 打开创建模态框
    const handleCreate = () => {
        setEditingTag(null);
        form.resetFields();
        setModalVisible(true);
    };

    const columns = [
        {
            title: '标签名称',
            dataIndex: 'name',
            key: 'name',
            hideInSearch: false,
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            valueEnum: {
                0: { text: '禁用', status: 'Default' },
                1: { text: '启用', status: 'Success' },
            },
        },
        {
            title: '排序',
            dataIndex: 'sort',
            key: 'sort',
            sorter: true,
        },
        {
            title: '创建时间',
            dataIndex: 'createdAt',
            key: 'createdAt',
            valueType: 'dateTime' as const,
            hideInSearch: true,
        },
        {
            title: '更新时间',
            dataIndex: 'updatedAt',
            key: 'updatedAt',
            valueType: 'dateTime' as const,
            hideInSearch: true,
        },
        {
            title: '操作',
            key: 'action',
            valueType: 'option' as const,
            render: (_: any, record: TagItem) => [
                <Button
                    key="edit"
                    type="link"
                    icon={<EditOutlined />}
                    onClick={() => handleEdit(record)}
                >
                    编辑
                </Button>,
                <Popconfirm
                    key="delete"
                    title="确定要删除这个标签吗？"
                    onConfirm={() => handleDelete(record.id)}
                    okText="确定"
                    cancelText="取消"
                >
                    <Button
                        type="link"
                        danger
                        icon={<DeleteOutlined />}
                    >
                        删除
                    </Button>
                </Popconfirm>,
            ],
        },
    ];

    return (
        <PageContainer>
            <ProTable<TagItem>
                headerTitle="商品标签管理"
                actionRef={actionRef}
                rowKey="id"
                search={{
                    labelWidth: 120,
                }}
                toolBarRender={() => [
                    <Button
                        key="create"
                        type="primary"
                        icon={<PlusOutlined />}
                        onClick={handleCreate}
                    >
                        新建标签
                    </Button>,
                ]}
                request={async (params) => {
                    try {
                        const response = await getProductTagList({
                            page: params.current || 1,
                            pageSize: params.pageSize || 10,
                            ...params,
                        });
                        
                        if (response?.data) {
                            return {
                                data: response.data.list || [],
                                success: true,
                                total: response.data.total || 0,
                            };
                        }
                        return {
                            data: [],
                            success: false,
                            total: 0,
                        };
                    } catch (error) {
                        return {
                            data: [],
                            success: false,
                            total: 0,
                        };
                    }
                }}
                columns={columns}
            />

            <Modal
                title={editingTag ? '编辑标签' : '新建标签'}
                open={modalVisible}
                onCancel={() => {
                    setModalVisible(false);
                    setEditingTag(null);
                    form.resetFields();
                }}
                footer={null}
            >
                <Form
                    form={form}
                    onFinish={handleSubmit}
                    layout="vertical"
                >
                    <Form.Item
                        name="name"
                        label="标签名称"
                        rules={[{ required: true, message: '请输入标签名称' }]}
                    >
                        <Input placeholder="请输入标签名称" />
                    </Form.Item>
                    
                    <Form.Item
                        name="status"
                        label="状态"
                        initialValue={1}
                    >
                        <Select>
                            <Select.Option value={1}>启用</Select.Option>
                            <Select.Option value={0}>禁用</Select.Option>
                        </Select>
                    </Form.Item>
                    
                    <Form.Item
                        name="sort"
                        label="排序"
                        initialValue={0}
                    >
                        <InputNumber min={0} style={{ width: '100%' }} />
                    </Form.Item>
                    
                    <Form.Item>
                        <Space>
                            <Button type="primary" htmlType="submit">
                                {editingTag ? '更新' : '创建'}
                            </Button>
                            <Button onClick={() => {
                                setModalVisible(false);
                                setEditingTag(null);
                                form.resetFields();
                            }}>
                                取消
                            </Button>
                        </Space>
                    </Form.Item>
                </Form>
            </Modal>
        </PageContainer>
    );
};

export default ProductTagPage; 